package com.cqgc.service.impl;

import com.cqgc.mapper.GoodsMapper;
import com.cqgc.mapper.OrderMapper;
import com.cqgc.mapper.ShoppingCartMapper;
import com.cqgc.mapper.UserMapper;
import com.cqgc.pojo.dto.ShoppingCartDTO.ShoppingCartDTO;
import com.cqgc.pojo.dto.ShoppingCartDTO.ShoppingCartDeleteDTO;
import com.cqgc.pojo.dto.ShoppingCartDTO.ShoppingCartPageDTO;
import com.cqgc.pojo.entity.*;
import com.cqgc.pojo.vo.ShoppingCartVO;
import com.cqgc.service.ShoppingCartService;
import com.cqgc.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

//    @Override
//    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
//        Map<String,Object> map = ThreadLocalUtil.get();
//        Integer uid= (Integer) map.get("uid");
//
//        shoppingCartMapper.findByGid()
//
//    }

    /**
     * 向购物车中添加商品。
     * <p>
     * shoppingCartDTO 购物车数据传输对象，包含商品id和供应商id等信息。
     * 该方法首先会根据传入的购物车DTO创建一个购物车实体对象，并复制DTO中的属性到实体中。
     * 接着，它会获取当前用户的身份ID，并将这个ID设置到购物车实体中。
     * 然后，它会检查购物车中是否已经存在该商品，如果不存在，则将商品数量设置为1并添加到购物车；
     * 如果已经存在，则将该商品的数量加1后更新购物车中的该商品记录。
     * 该方法不返回任何内容。
     */
    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        //创建一个购物车对象
        ShoppingCart shoppingCart = new ShoppingCart();
        //复制传过来的gid
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCart.setProviderId(goodsMapper.findById(shoppingCartDTO.getGid()).getCreateUser());
        //获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("uid");
        shoppingCart.setUid(id);
        //判断购物车内是否有此商品
        ShoppingCart shoppingCartMapperByGid = shoppingCartMapper.findByGid(shoppingCart.getGid(), id);
        if (shoppingCartMapperByGid != null && shoppingCartMapperByGid.getUid() == shoppingCart.getUid()) {

            shoppingCart.setQuantity(shoppingCartMapperByGid.getQuantity() + shoppingCartDTO.getQuantity());
            shoppingCartMapper.update(shoppingCart);

        } else {
            shoppingCartMapper.add(shoppingCart);
        }
    }

    @Override
    public PageResult list(ShoppingCartPageDTO shoppingCartPageDTO) {
        //获取登录用户的uid
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer uid = (Integer) map.get("uid");
        // 设置分页参数
        if (shoppingCartPageDTO.getPageNum() != 0 && shoppingCartPageDTO.getPageSize() != 0) {
            PageHelper.startPage(shoppingCartPageDTO.getPageNum(), shoppingCartPageDTO.getPageSize());
        }

        //根据用户id查询购物车
        Page<ShoppingCart> page = shoppingCartMapper.showShoppingCart(uid);
        //封装返回数据
        ArrayList<ShoppingCartVO> shoppingCartVOS = new ArrayList<>();
        for (ShoppingCart shoppingCart : page) {
            // 查询商品详细信息
            Goods goods = goodsMapper.findById(shoppingCart.getGid());
            if (goods == null) {
                continue;
            }
            ShoppingCartVO shoppingCartVO = new ShoppingCartVO();
            BeanUtils.copyProperties(goods, shoppingCartVO);
            User user = userMapper.findByUser(shoppingCart.getProviderId());
            // 计算商品的总价
            double totalPrice = shoppingCart.getQuantity() * goods.getPrice();
            // 构建并填充购物车VO对象
            ShoppingCartVO cartVO = shoppingCartVO.builder()
                    .gid(shoppingCart.getGid())
                    .quantity(shoppingCart.getQuantity())
                    .totalPrice(totalPrice)
                    .goodsName(goods.getGoodsName())
                    .price(String.valueOf(goods.getPrice()))
                    .nickName(user.getNickName())
                    .build();
            shoppingCartVOS.add(cartVO);
        }
        return new PageResult(page.getTotal(), shoppingCartVOS);


    }

    /**
     * 清理购物车。
     * 该方法首先尝试从ThreadLocal中获取当前线程的相关信息，确保操作的线程安全。接着，检查是否获取到了有效的用户ID（uid），并且该ID是Integer类型。
     * 如果满足条件，就尝试清理该用户的购物车；如果不满足条件，则输出相应的错误信息。
     * <p>
     * 该方法不接受任何参数。
     * <p>
     * 该方法没有返回值。
     */

    @Override
    public void cleanShoppingCart() {
        // 使用ThreadLocal获取当前线程的相关信息，确保线程安全
        Map<String, Object> map = ThreadLocalUtil.get();

        // 检查uid是否存在，并且是Integer类型
        Object uidObject = map.get("uid");
        if (uidObject != null && uidObject instanceof Integer) {
            Integer uid = (Integer) uidObject;

            try {
                // 尝试清理购物车，捕获可能的异常
                shoppingCartMapper.cleanShoppingCart(uid);
            } catch (Exception e) {

                System.out.println("清理购物车失败: " + e.getMessage());
            }
        } else {

            System.out.println("无法获取有效的用户ID");
        }
    }

    @Override
    public void deleteByGid(int gid) {
        // 使用ThreadLocal获取当前线程的相关信息，确保线程安全
        Map<String, Object> map = ThreadLocalUtil.get();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setGid(gid);
        shoppingCart.setUid((Integer) map.get("uid"));

        // 检查uid是否存在，并且是Integer类型
        Object uidObject = map.get("uid");
        if (uidObject != null && uidObject instanceof Integer) {
            Integer uid = (Integer) uidObject;

            try {
                // 尝试清理购物车，捕获可能的异常
                shoppingCartMapper.deleteByGid(shoppingCart);
            } catch (Exception e) {

                System.out.println("取消加入购物车失败: " + e.getMessage());
            }
        } else {

            System.out.println("无法获取有效的用户ID");
        }
    }

    @Override
    public void updateQuantity(ShoppingCartDTO shoppingCartDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUid((Integer) map.get("uid"));
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCartMapper.updateQuantity(shoppingCart);
        System.out.println("修改购物车数量成功");


    }

    @Override
    public int deleteByGids(ShoppingCartDeleteDTO shoppingCartDeleteDTO) {
        List<ShoppingCartList> gids = shoppingCartDeleteDTO.getGids();
        List<Integer> list = new ArrayList<>();
        gids.forEach(shoppingCartList -> list.add(shoppingCartList.getGid()));
        return shoppingCartMapper.deleteByGidS(list);
    }
}
